//
// Created by shen on 8/8/2024.
//

#include "NativeWindowRender.h"


NativeWindowRender::NativeWindowRender(JNIEnv *env, jobject surface)
        : VideoRender(VIDEO_RENDER_ANWINDOW) {

   m_NativeWindow = ANativeWindow_fromSurface(env,surface);
}


NativeWindowRender::~NativeWindowRender()
{
    if(m_NativeWindow)
        ANativeWindow_release(m_NativeWindow);

}
void NativeWindowRender::UnInit(){

}
void NativeWindowRender::Init(int videoWidth, int videoHeight, int *dstSize) {
    if (m_NativeWindow== nullptr){
        return;
    }

    int windoWidth= ANativeWindow_getWidth(m_NativeWindow);
    int windoHeight= ANativeWindow_getHeight(m_NativeWindow);

    if (windoWidth<windoHeight* videoWidth/videoHeight){
        m_DstWidth = windoWidth;
        m_DstHeight = windoWidth * videoHeight / videoWidth;
    }else{
        m_DstWidth = videoHeight * videoWidth / videoHeight;
        m_DstHeight = videoHeight;
    }

    ANativeWindow_setBuffersGeometry(m_NativeWindow,m_DstWidth
           ,m_DstHeight,WINDOW_FORMAT_RGBA_8888);
    dstSize[0] = m_DstWidth;
    dstSize[1] = m_DstHeight;
}

void NativeWindowRender::RenderVideoFrame(NativeImage *pImage) {
    if(m_NativeWindow == nullptr || pImage == nullptr) return;

    ANativeWindow_lock(m_NativeWindow,&m_NativeWindowBuffer, nullptr);
    uint8_t *dstBuffer = static_cast<uint8_t *>(m_NativeWindowBuffer.bits);

    int srcLineSize=pImage->width*4;  //解码出来的 每一行的大小
    int dstLineSize=m_NativeWindowBuffer.stride*4; // 目标的大小


    for (int i = 0; i < m_DstHeight; ++i){
        memcpy(dstBuffer + i * dstLineSize, pImage->ppPlane[0] + i * srcLineSize, srcLineSize);
    }

    ANativeWindow_unlockAndPost(m_NativeWindow);



}